import React, { Component } from 'react';
import {
  StyleSheet,
  Text, View,
  Animated,
  Easing,
  DeviceEventEmitter,
  Alert,
  TouchableOpacity,
} from 'react-native';
import { RNCamera } from 'react-native-camera';
import ImagePicker from 'react-native-image-crop-picker';
import LocalBarcodeRecognizer from 'react-native-local-barcode-recognizer';
import { Icon } from 'native-base';
import ZlstIcon from '../components/zlst-icons';
import theme from '../native-base-theme/variables';
import { UtilToast } from '../utils/util-method';

const tdata = {
  materialLotId: null,
  lotCode: '170400003486RX201812050001',
  inDate: '1543859941000',
  outDate: '1544003698000',
  supplierId: null,
  supplierName: null,
  manufacturerId: null,
  manufacturerName: null,
  materialId: '402892e4677d5ae101677d6e1d48501b',
  materialCode: null,
  materialName: '湖北金恒捣炉机配件：软管接头',
  materialSpecModel: '无',
  batchGranularity: 'BY_PACKAGE',
  photos: null,
  photos1: null,
  photos2: null,
};

class Qrcode extends Component {
  // static navigationOptions = {
  //   title: '条码扫描',
  //   headerStyle: { backgroundColor: theme.toolbarDefaultBg },
  //   headerTintColor: '#FFFFFF',
  //   headerTitleStyle: {
  //     fontWeight: 'bold',
  //     fontSize: 20,
  //     flex: 1,
  //     textAlign: 'center',
  //   },
  //   headerBackImage: (
  //     <ZlstIcon
  //       name="fanhui"
  //       size={24}
  //       color="white"
  //     />
  //   ),
  //   headerRight: <View />,
  // }

  static navigationOptions = ({ navigation }) => { // 给导航添加可点击的icon
    const edit = () => navigation.state.params.navigatePress();
    const editor = (
      <View style={{ flexDirection: 'row' }}>
        {/* <Icon name="ios-search" style={{ color: 'white', padding: 10 }} onPress={edit} /> */}
        <TouchableOpacity style={{ padding: 10 }} onPress={edit}>
          <Text style={{ color: 'white', fontSize: 16 }}>相册</Text>
        </TouchableOpacity>
      </View>
    );
    const headerStyle = {
      title: '条码扫描',
      headerStyle: { backgroundColor: theme.toolbarDefaultBg },
      headerTintColor: '#FFFFFF',
      headerTitleStyle: {
        fontWeight: 'bold',
        fontSize: 20,
        flex: 1,
        textAlign: 'center',
      },
      // headerRight: <View />,
      headerRight: editor,
    };
    return headerStyle;
  };

  flag = true;

  constructor(props) {
    super(props);
    this.state = {
      moveAnim: new Animated.Value(0),
    };
  }

  componentDidMount() {
    // const flag = this.props.navigation.state.params.flag;
    // alert(flag);
    this.props.navigation.setParams({ navigatePress: this.readImageQRCode });
    this.startAnimation();
  }

  readImageQRCode = () => {
    this.pickSingleBase64();
  }

  recoginze = async (v) => {
    const result = await LocalBarcodeRecognizer.decode(v, { codeTypes: ['ean13', 'qr'] });
    if (result) {
      Alert.alert(
        '提示',
        `识别图片二维码为:\n${result}`,
        [
          {
            text: '取消',
            style: 'cancel',
          },
          {
            text: '确定',
            onPress: () => {
              this.onBarCodeRead({ data: result });
            },
          },
        ],
      );
      // this.onBarCodeRead({ data: result });
    } else {
      UtilToast('扫描失败，请检查图片二维码是否正确', 'danger');
    }
  }

  pickSingleBase64 = async () => {
    ImagePicker.openPicker({
      width: 300,
      height: 300,
      cropping: true,
      includeBase64: true,
      compressImageQuality: 0.2,
    }).then(image => {
      console.log('received base64 image');
      this.recoginze(image.data);
    }).catch(e => alert(e));
  }

  //  识别二维码
  onBarCodeRead = (result) => {
    const { data } = result; // 只要拿到data就可以了
    // this.props.navigation.navigate({ routeName: 'About', params: { id: data } });
    if (this.flag) {
      this.flag = false;
      this.props.navigation.goBack();
      if (this.props.navigation.state.params.flag === 'incident') {
        this.props.navigation.navigate({ routeName: 'incidentSearch', params: { code: data, fromNavigation: true } });
      } else if (this.props.navigation.state.params.flag === 'device') {
        this.props.navigation.navigate({ routeName: 'deviceInfo', params: { code: data, fromNavigation: true } });
      } else if (this.props.navigation.state.params.flag === 'newIncident') {
        DeviceEventEmitter.emit('getDeviceInfoEvent', data);
      } else if (this.props.navigation.state.params.flag === 'part') {
        DeviceEventEmitter.emit('changpageQuery');
        this.props.navigation.navigate({ routeName: 'changeParts', params: { code: data, equipmentId: this.props.navigation.state.params.equipmentId, equipObjType: this.props.navigation.state.params.equipObjType } });
        // this.props.navigation.navigate({ routeName: 'changePartsConfirm', params: { downPart: { lotCode: '', materialName: 'materialName', splitCode: 'splitCode', splitItemId: 'splitItemId' }, upPart: tdata } });
      } else if (this.props.navigation.state.params.flag === 'maintainChangeMoreParts') {
        DeviceEventEmitter.emit('maintainChangeMoreParts', data);
      } else if (this.props.navigation.state.params.flag === 'task') {
        DeviceEventEmitter.emit('changpageQuery');
        this.props.navigation.navigate({ routeName: 'AddTaskDevice', params: { code: data, checkrecordId: this.props.navigation.state.params.checkrecordId } });
      } else if (this.props.navigation.state.params.flag === 'toInspectTaskDeviceDetail') {
        this.props.navigation.navigate({ routeName: 'PollingRecord', params: { data: { equipmentCode: data } } });
      } else if (this.props.navigation.state.params.flag === 'searchPart') {
        this.props.navigation.navigate({ routeName: 'SparePartInfo', params: { code: data } });
      } else if (this.props.navigation.state.params.flag === 'addPartEvent') {
        DeviceEventEmitter.emit('addPartEvent', data);
      } else if (this.props.navigation.state.params.flag === 'spitPart') {
        const params = {
          code: data,
        };
        global.navigation.navigate({ routeName: 'ChangePartInfo', params });
      }

      setTimeout(() => {
        this.flag = true;
      }, 2000);
    }
  };

  startAnimation = () => {
    this.state.moveAnim.setValue(0);
    Animated.timing(
      this.state.moveAnim,
      {
        toValue: -200,
        duration: 1500,
        easing: Easing.linear,
      },
    ).start(() => this.startAnimation());
  };

  render() {
    // const { id } = this.props.navigation.state.params;

    // return (
    //   <View style={styles.container}>
    //     <Text onPress={() => this.props.navigation.navigate({ routeName: 'PasswordReset' })}>
    //       Open up App.js to start working on your app!
    //     </Text>
    //     <Text>
    //       Changes you make will automatically reload.
    //     </Text>
    //     <Text>
    //       Shake your phone to open the developer menu.
    //     </Text>
    //   </View>
    // );
    return (
      <View style={styles.container}>
        <RNCamera
          ref={ref => {
            this.camera = ref;
          }}
          style={styles.preview}
          type={RNCamera.Constants.Type.back}
          flashMode={RNCamera.Constants.FlashMode.on}
          onBarCodeRead={(e) => this.onBarCodeRead(e)}
        >
          <View style={styles.rectangleContainer}>
            <View style={styles.rectangle} />
            <Animated.View style={[
              styles.border,
              { transform: [{ translateY: this.state.moveAnim }] }]}
            />
            <Text style={styles.rectangleText}>将二维码放入框内，即可自动扫描</Text>
          </View>
        </RNCamera>
      </View>
    );
  }
}

// const styles = StyleSheet.create({
//   container: {
//     flex: 1,
//     backgroundColor: '#fff',
//     alignItems: 'center',
//     justifyContent: 'center',
//   },
// });
const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
  },
  preview: {
    flex: 1,
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  rectangleContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'transparent',
  },
  rectangle: {
    height: 200,
    width: 200,
    borderWidth: 1,
    borderColor: '#00FF00',
    backgroundColor: 'transparent',
  },
  rectangleText: {
    flex: 0,
    color: '#fff',
    marginTop: 10,
  },
  border: {
    flex: 0,
    width: 200,
    height: 2,
    backgroundColor: '#00FF00',
  },
});

export default Qrcode;
